package cn.car91.service;

import java.io.ByteArrayInputStream;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.RemoteViews;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.bean.App;
import cn.car91.config.InitApplication;
import cn.car91.http.HttpHandler;
import cn.car91.utils.CheckStatusUtil;
import cn.car91.utils.MobileUtils;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.HerilyAlertDialog.Builder;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class UpdateService extends Service {

    private static final int NOTIFY_ID = 0;
    public static boolean isFirst = true;

    private NotificationManager mNotificationManager;
    Notification mNotification;
    ProgressDialog pd;    //进度条对话框

    private IBinder binder = new UpdateService.UpdateBinder();

    private Context context;

    private final String TAG = "Car91UpDate";
    private App app;
    private String pastVersionName = "";

    final int UPDATA_CLIENT = 0;
    final int GET_UNDATAINFO_ERROR = 1;
    final int DOWN_ERROR = 2;
    final int NOT_NEED_UPDATE = 3;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return binder;
    }

    @Override
    public void onCreate() {
        this.context = this;

        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            getVersionName();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        checkUpdate();
        return START_STICKY;
    }

    //定义内容类继承Binder
    public class UpdateBinder extends Binder {
        //返回本地服务
        UpdateService getService() {
            return UpdateService.this;
        }
    }

    public void checkUpdate() {
        HttpHandler.httpHandler.getCurApkVersion(callBackVersion);
    }

    private RequestCallBack callBackVersion = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            Log.e("update", arg0.toString());
            // 待处理   
            /*Message msg = new Message();  
            msg.what = GET_UNDATAINFO_ERROR;  
            handler.sendMessage(msg);  */
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            try {
                getUpdataInfo(arg0.result.toString());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (app != null) {
                Message msg = new Message();
                try {
                    if (app.getVersionName().equals(pastVersionName)) {
                        Log.i(TAG, "版本号相同无需升级");
                        msg.what = NOT_NEED_UPDATE;
                    } else {
                        Log.i(TAG, "版本号不同 ,提示用户升级 ");
                        msg.what = UPDATA_CLIENT;
                    }
                    handler.sendMessage(msg);
                } catch (Exception e) {
                }
            }
        }

    };

    /*
     * 获取当前程序的版本号
     */
    private void getVersionName() throws Exception {
        this.pastVersionName = MobileUtils.getVersionInfo(context);
    }

    /*
     * 获取服务器端的版本号
     * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
     */
    private void getUpdataInfo(String xml) throws Exception {
        //app = (App) Car91JsonUtil.getDTO(json, App.class);
        app = new App();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            ByteArrayInputStream inStream = new ByteArrayInputStream(xml.getBytes());
            Document dom = builder.parse(inStream);

            Element root = dom.getDocumentElement();
            try {
                app.setVersionName(root.getElementsByTagName("versionName").item(0).getTextContent());
            } catch (Exception e) {
            }
            try {
                app.setUpdateContent(root.getElementsByTagName("updateContent").item(0).getTextContent());
            } catch (Exception e) {
            }
            try {
                app.setAppName(root.getElementsByTagName("appName").item(0).getTextContent());
            } catch (Exception e) {
            }
            try {
                app.setSize(Long.parseLong(root.getElementsByTagName("size").item(0).getTextContent()));
            } catch (Exception e) {
            }

            inStream.close();
        } catch (Exception e) {
            Log.e("xmlException", e.toString());
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    Toast.makeText(context, "获取服务器更新信息失败", 1).show();
                    stopSelf();
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                	HerilyAlertDialog dialog_temp_down = new HerilyAlertDialog.Builder(context)
                            .setTitle("出错了")
                            .setMessage("下载新版本" + app.getAppName() + "失败")
                            .create();
                    dialog_temp_down.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    dialog_temp_down.show();
                    stopSelf();
                    break;
                case NOT_NEED_UPDATE:
                    //下载apk失败
                    if (!isFirst) {
                    	HerilyAlertDialog dialog_temp_update = new HerilyAlertDialog.Builder(context)
                                .setMessage("当前APP版本为" + pastVersionName + "最新版本").create();
                        dialog_temp_update.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        dialog_temp_update.show();
                    }
                    isFirst = false;
                    stopSelf();
                    break;
            }
        }
    };

    private static HerilyAlertDialog dialog;
    /*
     *
     * 弹出对话框通知用户更新程序
     *
     * 弹出对话框的步骤：
     *  1.创建alertDialog的builder.
     *  2.要给builder设置属性, 对话框的内容,样式,按钮
     *  3.通过builder 创建一个对话框
     *  4.对话框show()出来
     */
    protected void showUpdataDialog() {
        final String apkVersion = ((InitApplication) getApplication()).getOtherPreferences().getString("apkVersion", "");
        if (RegexUtil.isNotNull(apkVersion) && app.getVersionName().equals(apkVersion) && isFirst) {
            isFirst = false;
        } else {
        	HerilyAlertDialog.Builder builer = new HerilyAlertDialog.Builder(context);
            builer.setTitle("发现新版本 v" + app.getVersionName());
            builer.setMessage("更新内容：\n" + app.getUpdateContent());
            final Editor editor = ((InitApplication) getApplication()).getOtherPreferences().edit();
            //final CheckBox checkBox = (CheckBox) builer.getLayout().findViewById(R.id.rehint);
            //当点确定按钮时从服务器上下载 新的apk 然后安装
            builer.setPositiveButton("下载", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (CheckStatusUtil.getConnectedType(context) == ConnectivityManager.TYPE_MOBILE) {
                        final HerilyAlertDialog.Builder builer = new Builder(context);
                        builer.setTitle("提醒");
                        builer.setMessage("当前为非WIFI网络，是否继续下载");
                        //当点确定按钮时从服务器上下载 新的apk 然后安装
                        builer.setPositiveButton("继续下载", new OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                downLoadApk();
                            }
                        });
                        //当点取消按钮时进行登录
                        builer.setNegativeButton("取消", new OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                                stopSelf();
                            }
                        });
                        HerilyAlertDialog dialog_temp = builer.create();
                        dialog_temp.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        dialog_temp.show();
                    } else {
                        if (CheckStatusUtil.isNetworkConnected(context))
                            downLoadApk();
                        else
                            Toast.makeText(context, "当前无网络连接", Toast.LENGTH_LONG).show();
                    }
                }
            });
            //当点取消按钮时进行登录
            builer.setNegativeButton("取消", new OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                	/*try {
                		CheckBox checkBox =dialog.getReHint();
                		if (isFirst && checkBox.isChecked()) {
                            editor.putString("apkVersion", app.getVersionName());
                            editor.commit();
                        }
					} catch (Exception e) {
						// TODO: handle exception
					}*/
                    /*if (isFirst && checkBox.isChecked()) {
                        editor.putString("apkVersion", app.getVersionName());
                        editor.commit();
                    }*/
                    stopSelf();
                }
            });
            dialog = builer.create();
            
            /*if (isFirst) {
            	CheckBox checkBox =dialog.getReHint();
                checkBox.setText("该版本不再提示");
                ((View) checkBox.getParent()).setVisibility(View.VISIBLE);
            }*/

            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            dialog.show();
        }
    }

    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        pd.setIndeterminate(false);
        pd.setMax((int) app.getSize());
        pd.show();

        try {
            //final File file = getFileFromServer(versionUrl+"/car91.apk", pd);
            final File file = new File(Environment.getExternalStorageDirectory(), app.getAppName());
            HttpHandler.httpHandler.downUpdateApk(file.getAbsolutePath(), new RequestCallBack<File>() {
                        @Override
                        public void onStart() {
                            setUpNotification();
                            super.onStart();
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                            // TODO Auto-generated method stub
                            pd.setProgress((int) current);
                            RemoteViews contentview = mNotification.contentView;
                            int rate = (int) (100 * current / app.getSize());
                            contentview.setTextViewText(R.id.tv_progress, rate + "%");
                            contentview.setProgressBar(R.id.progressbar, (int) app.getSize(), (int) current, false);
                            mNotification.contentView = contentview;
                            // 通过消息管理器发送消息
                            mNotificationManager.notify(NOTIFY_ID, mNotification);
                            super.onLoading(total, current, isUploading);
                        }

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            // TODO Auto-generated method stub
                            Log.e(TAG, arg0.toString() + " " + arg1);
                            closeNotification();
                            pd.dismiss();
                            Message msg = new Message();
                            msg.what = DOWN_ERROR;
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onSuccess(ResponseInfo arg0) {
                            // TODO Auto-generated method stub
                            closeNotification();
                            pd.dismiss();
                            installApk(file);
                        }
                    }
            );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.toString());
            closeNotification();
            Message msg = new Message();
            msg.what = DOWN_ERROR;
            handler.sendMessage(msg);
        }
    }

    private void closeNotification() {
        try {
            mNotification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotification.contentView = null;
            PendingIntent contentIntent = PendingIntent.getActivity(UpdateService.this.getApplicationContext(), 0, new Intent(),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mNotification.setLatestEventInfo(UpdateService.this.getApplicationContext(), "下载完成", "文件已下载完毕", contentIntent);
            mNotificationManager.notify(NOTIFY_ID, mNotification);
        } catch (Exception e) {

        }
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    // 通知栏

    /**
     * 创建通知
     */
    private void setUpNotification() {
        int icon = R.drawable.ico_launcher;
        CharSequence tickerText = "开始下载";
        long when = System.currentTimeMillis();

        mNotification = new Notification(icon, tickerText, when);
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.view_download_notification);
        contentView.setTextViewText(R.id.name, app.getAppName() + " 正在下载...");
        // 指定个性化视图  
        mNotification.contentView = contentView; 
  /*
        Intent intent = new Intent(this, NotificationUpdateActivity.class);  
        // 下面两句是 在按home后，点击通知栏，返回之前activity 状态;  
        // 有下面两句的话，假如service还在后台下载， 在点击程序图片重新进入程序时，直接到下载界面，相当于把程序MAIN 入口改了 - -  
        // 是这么理解么。。。  
        // intent.setAction(Intent.ACTION_MAIN);  
        // intent.addCategory(Intent.CATEGORY_LAUNCHER);  
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,  
                PendingIntent.FLAG_UPDATE_CURRENT);  
  
        // 指定内容意图  
        mNotification.contentIntent = contentIntent;  */
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }
}
